package QC.MessageBox;

import QC.MessageBox.handler.*;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.*;

import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Andaren on 2017/3/31.
 * Used for: http服务主类
 */
public class MSGVerticle extends BaseVerticle {

    public static boolean ISDEBUG = false;

    private static final Logger LOGGER = LoggerFactory.getLogger(MSGVerticle.class);

    protected BeforeStartInitHandler beforeStartInitHandler;

    /*Called when verticle is deployed*/
    @Override
    public void start(Future<Void> fut) {

        super.start();

        // test reflect---------------------------------
        Map<String, Object> handlerMap = new HashMap<>();
        handlerMap.put("httpService", httpService);
        handlerMap.put("webClientService", webClientService);
        handlerMap.put("mySQLService", mySQLService);
        handlerMap.put("redisService", redisService);
        handlerMap.put("dataAccess", dataAccess);
        handlerMap.put("blockingService", blockingService);
        // test end--------------------------------------


        // ---------------------------------------------
        LOGGER.info(">>>>>>Doing init in the first time!<<<<<<");
        beforeStartInitHandler = new BeforeStartInitHandler(httpService,
                webClientService,
                mySQLService,
                redisService,
                dataAccess);
        if (ISDEBUG) {
            // TODO 正式时删除这段代码
        } else {
            beforeStartInitHandler
                    .doInitWorkInFirstTime()
                    .doPeriodicTask(vertx); // 每小时重新获取公众号调用服务API时需要的access_token
        }
        // 系统请求路由
        Router router = Router.router(vertx);
        // some rest API

        // 显式开启（读取请求体[:否则不能调用getBodyAsXXX方法]）
        router.route("/*").handler(BodyHandler.create());

        // 创建http服务
        HttpServer httpServer = vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(config().getInteger("port", 8686), res -> {
                    if (res.succeeded()) {
                        fut.complete();
                        LOGGER.info("Http服务创建完成");
                    } else {
                        fut.fail(res.cause());
                        LOGGER.info("Http服务创建失败");
                    }
                });


        // -------------test-----------------
        DispatherHandler dispatherHandler = new DispatherHandler(config(), router, handlerMap);
        dispatherHandler.loadJarFileAndInit();

    }

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        ISDEBUG = false;
        vertx.deployVerticle(new MSGVerticle(), new DeploymentOptions());

    }
}
